import logging
import os
from pathlib import Path
from datetime import timedelta
import pytz

# 获取项目根目录
BASE_DIR = Path(__file__).parent.parent  # 更安全的路径计算方式

# 定义密钥文件路径
PRIVATE_KEY_PATH = BASE_DIR / 'keys' / 'app_private_key.pem'
PUBLIC_KEY_PATH = BASE_DIR / 'keys' / 'alipay_public_key.pem'

# 读取密钥文件内容（项目启动时加载）
with open(PRIVATE_KEY_PATH, 'r') as f:
    APP_PRIVATE_KEY = f.read()

with open(PUBLIC_KEY_PATH, 'r') as f:
    ALIPAY_PUBLIC_KEY = f.read()


class BaseConfig:
    # 基础配置（开发环境）
    SECRET_KEY = os.getenv('SECRET_KEY', 'wwqq123456')  # 必须设置
    SQLALCHEMY_TRACK_MODIFICATIONS = False

    # MySQL 配置
    MYSQL_USERNAME = "root"
    MYSQL_PASSWORD = "123456"
    MYSQL_HOST = "127.0.0.1"
    MYSQL_PORT = 3306
    MYSQL_DATABASE = "firstweb"
    SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{MYSQL_USERNAME}:{MYSQL_PASSWORD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DATABASE}?charset=utf8mb4"

    # 插件配置，填写插件的文件名名称，默认不启用插件。
    PLUGIN_ENABLE_FOLDERS = []
    # 默认日志等级
    LOG_LEVEL = logging.WARN
    """
    flask-mail配置
    """
    MAIL_SERVER = 'smtp.qq.com'
    MAIL_USE_TLS = False
    MAIL_USE_SSL = True
    MAIL_PORT = 465
    MAIL_USERNAME = '123@qq.com'
    MAIL_PASSWORD = 'XXXXX'  # 生成的授权码
    MAIL_DEFAULT_SENDER = MAIL_USERNAME
    # 支付宝配置
    ALIPAY = {
        'APP_ID': '9021000145617417',  # 应用ID
        'APP_NOTIFY_URL': 'http://127.0.0.1:5050/cart/payment/notify',
        'RETURN_URL': 'http://127.0.0.1:5050/cart/payment/return',
        'APP_PRIVATE_KEY': APP_PRIVATE_KEY,  # 直接存储密钥内容
        'ALIPAY_PUBLIC_KEY': ALIPAY_PUBLIC_KEY,  # 直接存储密钥内容
        'SIGN_TYPE': 'RSA2',
        'DEBUG': True,  # 沙箱模式
        'GATEWAY': 'https://openapi-sandbox.dl.alipaydev.com/gateway.do?'  # 沙箱网关
    }
    # 上传文件配置
    UPLOADED_PHOTOS_DEST = 'static\\upload'  # 上传图片的默认路径
    UPLOADED_FILES_ALLOW = ['gif', 'jpg', 'png', 'jpeg', 'bmp', 'ico', 'webp']
    UPLOADS_AUTOSERVE = True  # 是否自动生成静态文件

    # Session 配置
    SESSION_TYPE = 'filesystem'
    SESSION_PERMANENT = False
    SESSION_USE_SIGNER = True
    SESSION_KEY_PREFIX = 'session:'
    PERMANENT_SESSION_LIFETIME = timedelta(minutes=30)  # 设置会话过期时间

    # 时区设置
    TIMEZONE = pytz.timezone('Asia/Shanghai')
    JWT_SECRET_KEY = 'jwt_secret_key_flask123321'  # 用于加密 JWT 的密钥
    JWT_EXPIRATION_DELTA = timedelta(days=1)  # JWT 的过期时间
    JWT_ACCESS_TOKEN_EXPIRES = timedelta(days=1, minutes=30)  # Access Token 过期时间
    JWT_REFRESH_TOKEN_EXPIRES = timedelta(days=7)  # Refresh Token 过期时间


def to_local_time(utc_dt):
    """将 UTC 时间转换为上海时间"""
    if not utc_dt:
        return None
    return utc_dt.replace(tzinfo=pytz.utc).astimezone(BaseConfig.TIMEZONE)



class TestingConfig(BaseConfig):
    # 测试环境配置
    TESTING = True
    SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'  # 使用内存 SQLite
    WTF_CSRF_ENABLED = False  # 测试时禁用 CSRF

    # 测试环境支付宝配置
    ALIPAY = {
        **BaseConfig.ALIPAY,
        'APP_NOTIFY_URL': 'http://test.domain/cart/payment/notify',
        'RETURN_URL': 'http://test.domain/cart/payment/return',
        'DEBUG': True,
    }


class ProductionConfig(BaseConfig):
    # 生产环境配置
    SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{BaseConfig.MYSQL_USERNAME}:{BaseConfig.MYSQL_PASSWORD}@{BaseConfig.MYSQL_HOST}:{BaseConfig.MYSQL_PORT}/prod_{BaseConfig.MYSQL_DATABASE}?charset=utf8mb4"
    # 生产环境支付宝配置
    ALIPAY = {
        **BaseConfig.ALIPAY,
        'APP_NOTIFY_URL': 'https://your-domain.com/cart/payment/notify',
        'RETURN_URL': 'https://your-domain.com/cart/payment/return',
        'DEBUG': False,  # 生产环境关闭调试模式
        'GATEWAY': 'https://openapi.alipaydev.com/gateway.do?'  # 沙箱网关
    }


# 配置字典（供应用工厂调用）
config = {
    'development': BaseConfig,
    'testing': TestingConfig,
    'production': ProductionConfig,
    'default': BaseConfig
}
